<template>
  <Content title="不良品处理详情">
    <view class="device-details" :style="data.id ? 'padding-bottom:150px' : ''">
      <template v-if="!data.id">
        <view class="no-data">
          <Empty text="无历史记录"></Empty>
        </view>
      </template>
      <view class="content" v-else>
        <view class="main-box">
          <u-form
            labelPosition="left"
            :model="model"
            labelWidth="85"
            labelAlign="left"
            :rules="rules"
            ref="uForm"
          >
            <view class="info-box">
              <view class="title">
                <text class="txt u-line-1">工单号 {{ id }}</text>
                <view class="tag-box">
                  <u-tag
                    shape="circle"
                    :text="data.state"
                    :borderColor="getColor(data.state)"
                    :bgColor="getColor(data.state)"
                  ></u-tag>
                </view>
              </view>

              <view class="text-box">
                <text class="label">产品编号:</text>
                <text class="value">{{ data.materialCode }}</text>
              </view>
              <view class="text-box">
                <text class="label">产品名称:</text>
                <text class="value">{{ data.materialName }}</text>
              </view>
              <view class="text-box">
                <text class="label">模具编号:</text>
                <text class="value">{{ data.moldCode }}</text>
              </view>
              <view class="text-box">
                <text class="label">模具名称:</text>
                <text class="value">{{ data.moldName }}</text>
              </view>
              <view class="text-box">
                <text class="label">计划数量:</text>
                <text class="value">{{ data.planProduceQuantity }}</text>
              </view>
              <view class="text-box">
                <text class="label">生产数量:</text>
                <text class="value">{{ data.produceQuantity }}</text>
              </view>
              <view class="text-box">
                <text class="label">不良品数量:</text>
                <text class="value">{{ data.defectiveProducts }}</text>
              </view>
              <view class="text-box">
                <text class="label">产品单重:</text>
                <text class="value">{{ data.weight }}</text>
              </view>
              <view class="text-box">
                <text class="label">重量单位:</text>
                <text class="value">{{ data.weightUnit }}</text>
              </view>
              <view class="text-box">
                <text class="label">不良描述:</text>
                <text class="value">{{ data.outReason }}</text>
              </view>
              <view class="text-box">
                <text class="label">报工人:</text>
                <text class="value">{{ data.operator }}</text>
              </view>
              <view class="text-box">
                <text class="label">报工时间:</text>
                <text class="value">{{ data.reportingTime }}</text>
              </view>
              <view class="text-box">
                <text class="label">备注:</text>
                <text class="value">{{ data.remarks }}</text>
              </view>
            </view>

            <view class="info-box">
              <view class="title">
                <text class="txt">处理结果</text>
              </view>
              <view class="text-box" style="margin-bottom: 0">
                <u-form-item label="" prop="checkResult" style="width: 100%"
                  ><!-- required -->
                  <u-radio-group
                    class="box-input"
                    v-model="model.checkResult"
                    @change="checkResultChange"
                  >
                    <u-radio
                      label="合格"
                      name="合格"
                      style="margin-right: 20px"
                    ></u-radio>
                    <u-radio label="不合格入库" name="不合格入库"></u-radio>
                    <u-radio
                      label="报废"
                      name="报废"
                      style="margin-right: 20px"
                    ></u-radio>
                    <u-radio label="返工" name="返工"></u-radio>
                  </u-radio-group>
                </u-form-item>
              </view>

              <view class="u-border-bottom" style="margin-bottom: 10px"></view>

              <view class="input-box">
                <u-form-item label="班次时间:" required prop="shiftTime">
                  <MyDate
                    @change="getShiftList"
                    v-model="model.shiftTime"
                    placeholder="请选择"
                  ></MyDate>
                </u-form-item>
              </view>
              <view class="input-box">
                <u-form-item label="班次:" required prop="shift">
                  <uni-data-select
                    v-model="model.shift"
                    :localdata="shiftList"
                    @change="getShiftTime"
                    placeholder="请选择"
                  ></uni-data-select>
                </u-form-item>
              </view>

              <view class="input-box">
                <u-form-item
                  required
                  :label="
                    model.checkResult === '报废'
                      ? '报废方式'
                      : model.checkResult === '返工'
                      ? '返工方式'
                      : '入库方式'
                  "
                  prop="warehousingMethod"
                >
                  <uni-data-select
                    v-model="model.warehousingMethod"
                    :localdata="wayList"
                    placeholder="请选择"
                  ></uni-data-select>
                </u-form-item>
              </view>
              <view
                class="input-box"
                v-if="model.warehousingMethod !== '按重量'"
              >
                <u-form-item
                  required
                  :label="
                    model.checkResult === '报废'
                      ? '报废数量'
                      : model.checkResult === '返工'
                      ? '返工数量'
                      : '入库数量'
                  "
                  prop="inNum"
                >
                  <u-input
                    class="box-input"
                    label
                    type="number"
                    v-model="model.inNum"
                    placeholder="请输入"
                    clearable
                  ></u-input>
                </u-form-item>
              </view>
              <view class="input-box" v-else>
                <u-form-item
                  required
                  :label="
                    model.checkResult === '报废'
                      ? '报废重量'
                      : model.checkResult === '返工'
                      ? '返工重量'
                      : '入库重量'
                  "
                  prop="inNum"
                >
                  <u-input
                    class="box-input"
                    label
                    type="number"
                    v-model="model.inNum"
                    placeholder="请输入"
                    clearable
                  ></u-input>
                </u-form-item>
              </view>
              <!-- <view class="text-box">
                <text class="label">重量单位:</text>
                <view class="value">{{ data.weight }} </view>
              </view> -->
              <view
                class="input-box"
                v-if="
                  !(
                    model.checkResult === '报废' || model.checkResult === '返工'
                  )
                "
              >
                <u-form-item label="入库仓库:" prop="inWarehouseName" required>
                  <uni-data-select
                    v-model="model.inWarehouseName"
                    @change="changeWareHouse"
                    :localdata="wareHouses"
                    placeholder="请选择"
                  ></uni-data-select>
                </u-form-item>
              </view>
            </view>

            <view class="info-box" v-if="model.checkResult === '报废'">
              <view class="title">
                <text class="txt">报废原因</text>
              </view>
              <view class="text-box" style="margin-bottom: 0">
                <u-form-item label="" prop="checkResult" style="width: 100%">
                  <u-radio-group class="box-input" v-model="model.changingType">
                    <u-radio
                      :label="item.value"
                      :name="item.value"
                      v-for="item in ngList"
                      :key="item"
                    ></u-radio>
                  </u-radio-group>
                </u-form-item>
              </view>
            </view>

            <view class="info-box">
              <view class="title">
                <text class="txt u-line-1">添加图片（选填，最多5张）</text>
              </view>
              <view class="text-box">
                <!-- <text class="label">填报数量:</text> -->
                <view class="value">
                  <MyUpload
                    v-model="fileList"
                    multiple
                    :maxCount="5"
                  ></MyUpload>
                </view>
              </view>
            </view>
          </u-form>
        </view>
      </view>

      <view class="btn-v" v-if="data.id">
        <view class="but-box">
          <u-button
            class="btn"
            @click="toPath"
            type="primary"
            text="查看历史记录"
          ></u-button>
          <u-button
            class="btn"
            type="primary"
            @click="submit"
            text="提交"
          ></u-button>
        </view>
      </view>
    </view>
  </Content>
</template>

<script>
import Content from "@/components/content/index";
import fetch from "@/utils/fetch";
import Empty from "@/components/empty";
import MyDate from "@/components/myDate.vue";
import { getNotice, setNotice } from "@/store/user.js";
import MyUpload from "@/components/myUpload";
import { setPageData, getPageData } from "@/store/user";
export default {
  components: {
    Content,
    MyDate,
    Empty,
    MyUpload,
  },
  data() {
    return {
      id: "",
      model: {
        checkResult: "合格",
        imagePath: "",
        inNum: "",
        shiftTime: this.$dayjs(new Date()).format("YYYY-MM-DD"),
        shift: "",
        shiftId: "",
        inWarehouseId: "",
        // operator: "",
        // outNumTotal: "",
        inWarehouseName: "",
        warehousingMethod: "按数量",
        // workOrder: "",
      },
      changingType: "",
      rules: {
        shift: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        shiftTime: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        warehousingMethod: {
          required: true,
          message: "请选择",
          trigger: ["blur", "change"],
        },
        inNum: {
          type: "number",
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
        outNumTotal: {
          type: "number",
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
        inWarehouseName: {
          required: true,
          message: "请填写",
          trigger: ["blur", "change"],
        },
      },
      navIndex: 0,
      type: "1",
      data: {},
      fileList: [],
      shiftList: [],
      ngList: [],
      inWarehouseNameList: [],
      wayList: [
        {
          text: "按数量",
          value: "按数量",
        },
        {
          text: "按重量",
          value: "按重量",
        },
      ],
      isReady: true,
      wareHouses: [],
      obj: {}, // 页面跳转时传递的参数
    };
  },
  watch: {},
  onLoad: function (option) {
    //option为object类型，会序列化上个页面传递的参数
    this.obj = getPageData() || {};
    this.id = this.obj.workCode;
  },
  onShow: function () {
    if (this.isReady) return;
    this.getList();
  },
  onReady: function () {
    this.isReady = false;
    this.getList();
    this.getPoorList();
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    if (this.$refs.uForm) this.$refs.uForm.setRules(this.rules);
  },
  mounted() {},
  methods: {
    checkResultChange(val) {
      console.log("checkResultChange", val);
      if (val === "合格" || val === "不合格入库") {
        this.getWareHouseList();
      }
      //   if (val === "合格" || val === "不合格入库") {
      //     this.$set(this.rules, "inWarehouseName", {
      //       required: true,
      //       message: "请填写",
      //       trigger: ["blur", "change"],
      //     });
      //   } else {
      //     delete this.rules.inWarehouseName;
      //   }
    },
    getColor(item2) {
      return item2 == "待排产"
        ? "#E5963A"
        : item2 == "已排产"
        ? "#998BF2"
        : item2 == "下发"
        ? "#6BBEE1"
        : item2 == "生产"
        ? "#73D8A6"
        : item2 == "中断"
        ? "#D48B3E"
        : item2 == "暂停"
        ? "#D8BE49"
        : item2 == "完成"
        ? "#4668E2"
        : item2 == "转产中"
        ? "#E794C9"
        : item2 == "转产完成"
        ? "#C25BC6"
        : item2 == "调机中"
        ? "#D8B2F2"
        : item2 == "调机完成"
        ? "#8698F6"
        : item2 == "拆模"
        ? "#EA709F"
        : "#31b099";
    },
    getList() {
      fetch("get", "/dms/mobileEnd/getWorkSelfCheckList", {
        workOrder: this.id,
        defectiveNumber: this.obj.defectiveNumber,
      }).then((res) => {
        this.data = res.data || {};

        this.model.shift = res.data.shift;
        this.model.shiftTime =
          res.data.shiftTime || this.$dayjs(new Date()).format("YYYY-MM-DD");
        this.getShiftList();
        this.getWareHouseList();
      });
    },
    getShiftTime(val, data) {
      console.log("getShiftTime", val, data);
      this.model.shiftId = data.id;
    },
    changeWareHouse(val, data) {
      console.log("changeWareHouse", val, data);
      this.model.inWarehouseId = data.id;
    },
    //班次列表
    getShiftList() {
      const that = this;
      fetch("get", "/dms/mobile/getShiftList", {
        deviceNo: that.data.deviceCode,
        shiftDate: that.model.shiftTime,
      }).then((res) => {
        const now = that.$dayjs().format("YYYY-MM-DD") + " ";
        const newDate = that.$dayjs().format("YYYY-MM-DD HH:mm:ss");
        const now1 = that.$dayjs().add(1, "day").format("YYYY-MM-DD") + " ";
        that.shiftList = res.data.map((item) => {
          const startTime = now + item.shiftStartTime;
          let endTime = now + item.shiftEndTime;
          if (endTime < startTime) {
            endTime = now1 + item.shiftEndTime;
          }
          console.log("startTime, endTime", startTime, endTime, newDate);
          if (newDate > startTime && newDate < endTime) {
            that.model.shift = item.shift;
            that.model.shiftId = item.id;
          }
          return {
            ...item,
            value: item.shift,
            text: item.shift,
          };
        });
        if (!that.model.shift) {
          that.model.shift = that.shiftList[0].shift;
          that.model.shiftId = that.shiftList[0].id;
        }

        console.log("that.shiftList", that.shiftList);
      });
    },
    getWareHouseList() {
      fetch(
        "get",
        this.model.checkResult == "合格"
          ? "/dms/mobileEnd/getQualifiedWarehouse"
          : "/dms/mobileEnd/getDefectiveWarehouse",
        {
          deviceNo: this.data.deviceCode,
        }
      ).then((res) => {
        this.wareHouses = [res.data].map((item) => ({
          value: item.backupName,
          text: item.backupName,
        }));
        this.model.inWarehouseName = res.data.backupName;
        this.model.inWarehouseId = res.data.id;
      });
    },
    getPoorList() {
      const that = this;
      this.ngList = [];
      fetch("get", "/dms/faultCategory/dictList", {
        name: "报废",
      }).then((res) => {
        // that.$set(that.model,'changingType',null)
        that.ngList = res.data;
      });
    },
    toPath() {
      uni.navigateTo({
        url:
          "/pages/staging/handling-defective-products/reporting-records?workOrder=" +
          this.id,
        animationType: "pop-in",
      });
    },
    submit() {
      const that = this;
      this.$refs.uForm.validate().then((valid) => {
        if (valid) {
          that.$loading.open();
          let data = {
            ...this.model,
            inNum: this.model.inNum - 0,
            workCode: this.data.workCode,
            defectiveNumber: this.obj.defectiveNumber,
            imagePath: that.fileList.map((item) => {
              return {
                ...item,
                fileName: item.fileName,
                filePath: item.url,
                fileUrl: item.url,
              };
            }),
          };
          fetch("post", "/dms/mobileEnd/addWorkSelfCheck", data).then(
            (data) => {
              that.$loading.close();
              uni.$emit("openToast", {
                type: "success",
                title: "申请成功",
                complete() {
                  uni.navigateBack({
                    delta: 1,
                  });
                },
              });
            }
          );
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.device-details {
  height: 100%;
  overflow: auto;

  .content {
    min-height: 100%;
  }

  .title {
    font-size: 32rpx;
    margin-bottom: 20rpx;
    padding: 0 40rpx 20rpx 40rpx;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;

    .txt {
      flex: 1;
    }

    .tag-box {
      display: flex;
      align-items: center;
    }
  }

  .content-top {
    padding: 40rpx;

    .state {
      color: #f17a0a;
      margin-bottom: 20rpx;
    }
  }

  .info-box .text-box .label {
    width: 85px;
  }

  .search-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 60rpx;

    .label {
      margin: 0 20rpx;
    }
  }
}
</style>
